package uoc.biblioteca.service;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SendFileByFTP {


	private static final Log log = LogFactory.getLog(SendFileByFTP.class);
	
	public static boolean sendPorSFTP(String fileName,String localPathProperties,String filePathDownload) throws Exception {
		
		
		// TODO code application logic here

	       String username = null;
	       String host = null;
	       String pass = null;
	       //String khfile = "/ssh/known_hosts";
	       //String identityfile = "/ssh/id_rsa";
	       
	       host = obtenirDadesFtp("server", localPathProperties);
	       username = obtenirDadesFtp("user", localPathProperties);
		   pass = obtenirDadesFtp("pass", localPathProperties);
			
		   String fdest = obtenirDadesFtp("path", localPathProperties) +fileName;

	       JSch jsch = null;
	       Session session = null;
	       Channel channel = null;
	       ChannelSftp c = null;
	       try {
	    	   
	    	   java.util.Properties config = new java.util.Properties(); 
	    	   config.put("StrictHostKeyChecking", "no");
	    	   
	    	   
	           jsch = new JSch();
	           session = jsch.getSession(username, host, 22);
	           session.setPassword(pass);
	           session.setConfig(config);
	           //jsch.setKnownHosts(localPathProperties+khfile);
	           //jsch.addIdentity(localPathProperties+identityfile);
	           session.connect();

	           channel = session.openChannel("sftp");
	           channel.connect();
	           c = (ChannelSftp) channel;

	       } catch (Exception e) { 	e.printStackTrace();	}

	       try {
	           String fsrc = filePathDownload+"/"+fileName;
	           
	           c.put(fsrc, fdest);
	       
	           c.get(fdest,fsrc );
	       } catch (Exception e) {	e.printStackTrace();	}
	       
	       c.disconnect();
	       session.disconnect();
	       return true;

		
	}
	
    public static String obtenirDadesFtp(String key,String localPathProperties){
	    
	    Properties prop = new Properties();
	    String property = null;	
	    
	    
	    try {
	    	File f=(new File((localPathProperties+"/ftp.properties")));
	    	FileInputStream archivo = new FileInputStream(f);
	    	prop.load(archivo);   	// Cargo propiedades
	    	
	    	// Lectura de propiedad
			property = prop.getProperty(key);
	    }
	    
	    catch (Exception e) {
			e.printStackTrace();
		}
	  	
	    return property;
	   
  }

}
